package cn.edu.zafu.bigdata.x.zcy_0217;

import java.io.*;
import java.net.*;

public class Client {
    public static void main(String[] args) throws IOException {
        String hostname = "127.0.0.1"; // 服务端IP地址
        int port = 1234; // 服务端端口号

        Socket socket = new Socket(hostname, port);
        System.out.println("Connected to server.");

        InputStream input = socket.getInputStream();
        OutputStream output = socket.getOutputStream();

        new Thread(new ClientReader(input)).start();

        BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
        String userInput;
        while ((userInput = stdIn.readLine()) != null) {
            output.write(userInput.getBytes());
            output.write("\n".getBytes());
            output.flush();
        }

        socket.close();
    }

    private static class ClientReader implements Runnable {
        private InputStream inputStream;

        public ClientReader(InputStream inputStream) {
            this.inputStream = inputStream;
        }

        public void run() {
            try {
                byte[] buffer = new byte[1024];
                while (true) {
                    int bytesRead = inputStream.read(buffer);
                    if (bytesRead == -1) {
                        break;
                    }

                    String serverResponse = new String(buffer, 0, bytesRead);
                    System.out.println("Server: " + serverResponse);
                }
            } catch (IOException e) {
                System.out.println("Error in client reader: " + e.getMessage());
            }
        }
    }
}
